package com.suqiu.qqrobot.service.impl;


import com.suqiu.qqrobot.common.log.annotation.LogMgr;
import com.suqiu.qqrobot.model.ImageMessage;
import com.suqiu.qqrobot.model.Message;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.entity.images.Image;
import com.unfbx.chatgpt.entity.images.ImageResponse;
import lombok.RequiredArgsConstructor;
import love.forte.simbot.message.ResourceImage;
import love.forte.simbot.resources.FileResource;
import love.forte.simbot.resources.Resource;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

@LogMgr
@RequiredArgsConstructor
@Service("openAiImageModelService")
public class OpenAiImageModelService implements OpenAiChatService<String, ResourceImage> {

    private final OpenAiClient openAiClient;
    private final static String BASE_URL = "C:\\Users\\Administrator\\Desktop\\pic\\";

    @Override
    public Message<ResourceImage> chat(String sessionId, String question) throws IOException {
        // chat-gpt
        Image image = Image.builder().prompt(question).size("512x512").user(sessionId).build();
        ImageResponse imageResponse = openAiClient.genImages(image);

        URL url = new URL(imageResponse.getData().get(0).getUrl());
        BufferedImage bufferedImage = ImageIO.read(url);
        File outputFile = new File(BASE_URL + UUID.randomUUID() + ".png");
        ImageIO.write(bufferedImage, "png", outputFile);

        FileResource resource = Resource.of(outputFile);
        ResourceImage resultImage = love.forte.simbot.message.Image.of(resource);

        Message<ResourceImage> imageMessage = new ImageMessage();
        imageMessage.setMessage(resultImage);
        return imageMessage;
    }
}
